package com.rub.android.ui.activity

import android.content.Intent
import android.hardware.Camera
import android.os.Bundle
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.rub.android.R
import java.io.File
import java.io.FileOutputStream
import java.io.IOException


class CameraActivity : AppCompatActivity() {


    private var sfvPreview: SurfaceView? = null
    private var btnTake: Button? = null
    private var camera: Camera? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_camera)
        bindViews()
    }

    private val holderCallback: SurfaceHolder.Callback = object : SurfaceHolder.Callback {
        override fun surfaceCreated(holder: SurfaceHolder) {
            startPreview()
        }

        override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {}
        override fun surfaceDestroyed(holder: SurfaceHolder) {
            stopPreview()
        }

    }

    private fun stopPreview() {
        camera?.stopPreview()
        camera?.release()
        camera = null
    }

    private fun bindViews() {
        sfvPreview = findViewById(R.id.sfv_preview1)
        btnTake = findViewById(R.id.btn_take1)
        sfvPreview?.holder?.addCallback(holderCallback)
        btnTake?.setOnClickListener {

            camera!!.takePicture(null, null, { data, _ ->
                var path: String? = ""
                if (saveFile(data).also { path = it } != null) {
                    val it = Intent(this, PreviewActivity::class.java)
                    it.putExtra("path", path)
                    startActivity(it)
                } else {
                    Toast.makeText(this, "保存照片失败", Toast.LENGTH_SHORT).show()
                }
            })


        }
    }

    //保存临时文件的方法
    private fun saveFile(bytes: ByteArray): String? {
        try {
            val file: File = File.createTempFile("img", "")
            val fos = FileOutputStream(file)
            fos.write(bytes)
            fos.flush()
            fos.close()
            return file.absolutePath
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return ""
    }

    private fun startPreview() {
        camera = Camera.open()

        try {
            camera!!.setPreviewDisplay(sfvPreview?.holder)
            camera!!.setDisplayOrientation(90) //让相机旋转90度
            camera!!.startPreview()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

}